﻿using DB2WORD.Models;
using Newtonsoft.Json;

namespace DB2WORD
{
    public partial class UcProject : UserControl
    {
        private readonly Project project;
        public string ProjectID { get { return this.project.ID; } }

        public UcProject()
        {
            InitializeComponent();
        }

        public UcProject(Project project) : this()
        {
            this.project = project;

            this.btnColumns.Enabled = false;

            this.btnTables.Click += async (_, _) => MainForm.Self.Detail(this.project);
            this.btnColumns.Click += async (_, _) => MainForm.Self.Edit(this.project);
            this.btnDelete.Click += async (_, _) => Deleted.Invoke(this, EventArgs.Empty);
        }

        public event EventHandler<EventArgs> Deleted;

        private void LoadMessage()
        {
            try
            {
                var jsonFileName = $"{this.project.Name}.json";
                if(File.Exists(jsonFileName))
                {
                    var jsonText = File.ReadAllText(jsonFileName);
                    var groups = JsonConvert.DeserializeObject<List<GroupInfo>>(jsonText);
                    if(groups != null)
                    {
                        var tablesCount = groups.Sum(x => x.Tables?.Count() ?? 0);
                        this.lblMessage.Text = $"计 {groups.Count} 个模块，{tablesCount} 个表";
                        this.btnColumns.Enabled = tablesCount > 0;
                        return;
                    }
                }
                this.lblMessage.Text = "未保存文档";
            }
            catch(Exception ex)
            {
                this.lblMessage.Text = $"错误：{ex.Message}";
                MainForm.Self.toolTip.SetToolTip(this.lblMessage, ex.Message);
            }
        }

        public void RefreshInfo()
        {
            this.lblVersion.Text = $"版本号：{project.Version}  --  更新时间：{(project.LastUpdateTime ?? project.CreateTime):yyyy-MM-dd HH:mm:ss}";
            this.lblName.Text = $"> {project.Name}";
            this.lblMessage.Text = "计算中...";
            Task.Run(() => LoadMessage());
        }
    }
}
